/**
 * Created by waterworld on 16-9-27.
 */
var P = require("bluebird");
var wilddog=P.promisifyAll(require('wilddog'));
var wilddogBackup=P.promisifyAll(require('wilddog'));
var cnst=require('./../../../shared/const');

var wilddogSafe = module.exports;
wilddogSafe.init=function(cb)
{
    wilddog.initializeApp(cnst.wilddogConfig);
    wilddogBackup.initializeApp(cnst.wilddogSafeConfig);
    this.wilddog=wilddog;
    this.wilddogBackup=wilddogBackup;
    var workAsync= P.coroutine(function*()
    {
        var res=yield wilddog.auth().signInWithEmailAndPassword(cnst.wilddogConfig.account, cnst.wilddogConfig.password);
        //res=yield wilddogBackup.auth().signInWithEmailAndPassword(cnst.wilddogConfig.account, cnst.wilddogConfig.password);
        if(cb){ cb();}

    });
    workAsync();

};



wilddogSafe.getDataAsync= P.coroutine(function*(path)
{
    if(!this.wilddog)
    {   return null;
    }
    var ref=this.wilddog.sync().ref(path);
    var getDataAsync=new Promise(function(resolveFuncRet, rejectErr) {ref.once("value", resolveFuncRet);});
    var data=yield getDataAsync.then(function(data){ return data;});
    return data.val();
});


wilddogSafe.update= P.coroutine(function*(path,value){
    var ref = this.wilddog.sync().ref(path);//获取节点
    var ref1=this.wilddogBackup.sync().ref(path);
    var updateAsync=new Promise(function(resolveFuncRet, rejectErr) {ref.update(value, resolveFuncRet);});
    //var updateAsync1=new Promise(function(resolveFuncRet, rejectErr) {ref1.update(value, resolveFuncRet);});
    try
    {   var ret= yield updateAsync.then(function(err){ if(err==null) return true;else return false;});
       // yield updateAsync1.then(function(err){ if(err==null) return true;else return false;});
        return ret;
    }
    catch(e)
    { return false;
    }
});

wilddogSafe.remove= P.coroutine(function*(path){
    var ref=this.wilddog.sync.ref(path);
    ref.remove();
});
